﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;

/// <summary>
/// DependencyObject类的扩展方法类
/// </summary>
 public static class DependencyObjectExtensions
{

     /// <summary>
     /// 查找给定元素指定类型的父类
     /// </summary>
     /// <typeparam name="T">父类型</typeparam>
     /// <param name="obj"></param>
     /// <returns>父类</returns>
     public static T FindParent<T>(this DependencyObject obj) where T : DependencyObject
     {
         return obj.GetAncestors().OfType<T>().FirstOrDefault();
     }

    /// <summary>
    /// 查找可视对象的所有迭代父类
    /// </summary>
    /// <param name="element">要查找父对象的元素</param>
    /// <returns>可视父类集合</returns>
    /// <remarks>返回的集合包括传入的参数element.</remarks>
    public static IEnumerable<DependencyObject> GetAncestors(this DependencyObject element)
    {
        do
        {
            yield return element;
            element = VisualTreeHelper.GetParent(element);
        } while (element != null);
    }

    /// <summary>
    /// 返回指定条件的父类
    /// </summary>
    /// <param name="element"></param>
    /// <param name="condition"></param>
    /// <returns></returns>
    public static DependencyObject FindParent(this DependencyObject element, Predicate<DependencyObject> condition)
    {
        while (element != null)
        {
            if (condition(element))
            {
                return element;
            }
            element = VisualTreeHelper.GetParent(element);
        }
        return null;
    }
}

